﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dorm.QueryObject
{
    public class Select
    {
        protected string _prefix { get; set; }
        protected string _from { get; set; }
        protected string _join { get; set; }
        protected string _where { get; set; }
        protected string _orderBy { get; set; }

        public Select(string prefix) { _prefix = prefix; }

        public Select(params string[] fields)
        {
            foreach (var field in fields)
                _prefix = field + ", \r\n";
            _prefix.Remove(_prefix.Length - 2, 2);
        }

        public Select From(string from)
        {
            _from = from;
            return this;
        }

        public Select Join(string foreignTable, string equalityExpression)
        {
            return Join(JoinType.INNER, foreignTable, equalityExpression);
        }

        public Select Join(JoinType type, string foreignTable, string equalityExpression)
        {
            _join += type + " JOIN " + foreignTable + " ON " + equalityExpression + "\r\n";
            return this;
        }

        public Select Where(string where)
        {
            _where += where + "\r\n";
            return this;
        }

        public Select OrderBy(string orderBy)
        {
            _orderBy += orderBy + "\r\n";
            return this;
        }

        public override string ToString()
        {
            var sql = new StringBuilder();
            string tab = "    ";

            sql.AppendLine("SELECT");
            if (_prefix == null)
                sql.AppendLine(tab + "*");
            else
                sql.AppendLine(tab + _prefix);

            sql.AppendLine("FROM " + _from);

            if (_join != null)
            {
                sql.AppendLine(_join);
            }

            if (_where != null)
            {
                sql.AppendLine("WHERE");
                sql.AppendLine(_where);
            }

            if (_orderBy != null)
            {
                sql.AppendLine("ORDER BY");
                sql.AppendLine(_orderBy);
            }

            return sql.ToString();
        }
    }
}
